package com.qf.controller;

import com.sun.deploy.net.HttpResponse;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author bss
 * @version V1.0
 * @Project maven
 * @Package com.qf.controller
 * @Description:
 * @Date 2022/10/8 17:31
 */
@Controller
public class UploadController {

    @RequestMapping("/upload/test1")
    public String upLoad(String name, MultipartFile file,HttpSession session){

        String uuid = UUID.randomUUID().toString();

        String filename = file.getOriginalFilename();
        String[] split = filename.split("[.]");
        String extend = split[split.length - 1];
        String servletName = uuid +"."+ extend;

        String realPath = session.getServletContext().getRealPath("/img");
        File path = new File(realPath);
        if (!path.exists()){
            path.mkdirs();
        }
        try {
            file.transferTo(new File(path,servletName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "/index.jsp";
    }

    @RequestMapping("/download/test1")
    public void download(HttpServletResponse response, String name) throws IOException {
        response.setHeader("content-disposition","attachment;filename="+name);

        IOUtils.copy(new FileInputStream("d:\\1.png"),response.getOutputStream());
    }
}
